/*
 * Author: 李波（Edwin Lee)
 * Date: 2024-06-19 18:51:59
 * FilePath: /chat/src/server/model/friendmodel.cc
 * LastEditTime: 2024-07-13 18:00:20
 * version: 1.0
 * Description: 
 */
#include "friendmodel.h"
//#include "db.h"
#include "user.hpp"
#include "connection.h"
#include "commonConnectionPool.h"
#include <muduo/base/Logging.h>

void FriendModel::insert(int userid, int friendid)
{
    //组装sql语句
    char sql[1024] = {0};
    sprintf(sql,"insert into friend values(%d,%d)",userid, friendid);
    ConnectionPool& cnp = ConnectionPool::getInstance();
    shared_ptr<Connection> conn = cnp.getConnection();
    if(conn == nullptr)
    {
        LOG_FATAL << "cnp.getConnection failed";
        return;
    }
    conn->update(sql);
}

vector<User> FriendModel::query(int userid)
{
    //组装sql语句
    char sql[1024] = {0};
    sprintf(sql,"select u.id,u.name,u.state from user u inner join (select * from friend where \
        userid =%d) a on u.id = a.friendid",userid);

    ConnectionPool& cnp = ConnectionPool::getInstance();
    shared_ptr<Connection> conn = cnp.getConnection();
    vector<User> vuser;
    User user;
    if(conn != nullptr)
    {
        MYSQL_RES* res = conn->query(sql);
        if(res != nullptr)
        {
            MYSQL_ROW row;
            while((row = mysql_fetch_row(res)) != nullptr)
            {
                user.setId(atoi(row[0]));
                user.setName(row[1]);
                user.setState(row[2]);
                vuser.push_back(user);
            }
            mysql_free_result(res);
        }
    }
    return vuser;
}